package com.java.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.java.enums.TransTypeEnum;
import com.java.exceptioin.Assert;
import com.java.hfb.FormHelper;
import com.java.hfb.HfbConst;
import com.java.hfb.RequestHelper;
import com.java.instans.MqConst;
import com.java.mapper.UserInfoMapper;
import com.java.pojo.bo.TransFlowBO;
import com.java.pojo.entity.UserAccount;
import com.java.mapper.UserAccountMapper;
import com.java.pojo.entity.UserInfo;
import com.java.vo.SmsDTO;
import com.java.result.ResponseEnum;
import com.java.service.RabbitService;
import com.java.service.TransFlowService;
import com.java.service.UserAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.service.UserInfoService;
import com.java.utils.LendNoUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户账户 服务实现类
 * </p>
 *
 * @author Helen
 * @since 2021-07-08
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private TransFlowService transFlowService;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserAccountService userAccountService;

    @Resource
    private RabbitService rabbitService;

    @Resource
    private UserInfoService userInfoService;

    //充值
    @Override
    public String commitCharge(BigDecimal chargeAmt, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);

        //组装数据
        Map<String, Object> param = new HashMap<>();
        param.put("agentId", HfbConst.AGENT_ID);
        //流水编号
        param.put("agentBillNo", LendNoUtils.getChargeNo());
        //充值人绑定协议号
        param.put("bindCode", userInfo.getBindCode());
        //充值金额
        param.put("chargeAmt", chargeAmt);
        param.put("feeAmt", new BigDecimal(0));
        //通知商户充值成功的完整地址
        param.put("notifyUrl", HfbConst.RECHARGE_NOTIFY_URL);
        //返回地址
        param.put("returnUrl", HfbConst.RECHARGE_RETURN_URL);
        param.put("timestamp", RequestHelper.getTimestamp());
        param.put("sign", RequestHelper.getSign(param));

        //将数据组装到表单
        String buildForm = FormHelper.buildForm(HfbConst.RECHARGE_URL,param);
        return buildForm;
    }


    //充值同步
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String Commitnotify(Map<String, Object> map) {
        String agentBillNo = (String)map.get("agentBillNo");
        //幂等性判断 标准：判断交易流水是否存在
        Boolean isSaveTransFlow = transFlowService.isSaveTransFlow(agentBillNo);
        if(isSaveTransFlow){
            return "success";
        }
        String bindCode = (String)map.get("bindCode");
        String chargeAmt = (String)map.get("chargeAmt");
        userInfoMapper.updateAmount(bindCode,new BigDecimal(chargeAmt),new BigDecimal(0));

        //充值成功后发送业务短信 手机号 消息内容
        SmsDTO smsDTO = new SmsDTO();
        String moblie = userInfoService.getMobileByBindCode(bindCode);
        smsDTO.setMobile(moblie);
        smsDTO.setMessage("充值成功");
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,smsDTO);

        //记录交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(chargeAmt),
                TransTypeEnum.RECHARGE,
                "充值"
        );
        transFlowService.saveTransFlow(transFlowBO);
        return "success";
    }

    @Override
    public BigDecimal getAmount(Long userId) {
        QueryWrapper<UserAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        UserAccount userAccount = userAccountMapper.selectOne(wrapper);
        return userAccount.getAmount();
    }

    //提现
    @Override
    public String withdrasCommit(BigDecimal chargeAmt, Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);

        BigDecimal amount = userAccountService.getAmount(userId);
        //校验提现的余额是否比当前余额小
        Assert.isTrue(amount.doubleValue() >=  chargeAmt.doubleValue(), ResponseEnum.NOT_SUFFICIENT_FUNDS_ERROR);

        //组装数据
        Map<String, Object> param = new HashMap<>();
        param.put("agentId", HfbConst.AGENT_ID);
        //流水编号
        param.put("agentBillNo", LendNoUtils.getWithdrawNo());
        //提现人绑定协议号
        param.put("bindCode", userInfo.getBindCode());
        //提现金额
        param.put("fetchAmt", chargeAmt);
        //提现费用
        param.put("feeAmt", new BigDecimal(0));
        //通知商户充值成功的完整地址
        param.put("notifyUrl", HfbConst.WITHDRAW_NOTIFY_URL);
        //返回地址
        param.put("returnUrl", HfbConst.WITHDRAW_RETURN_URL);
        param.put("timestamp", RequestHelper.getTimestamp());
        param.put("sign", RequestHelper.getSign(param));

        //将数据组装到表单
        String buildForm = FormHelper.buildForm(HfbConst.WITHDRAW_URL,param);
        return buildForm;
    }

    //提现的回调接口
    @Override
    public String notifyWithdraw(Map<String, Object> map) {
        String agentBillNo = (String)map.get("agentBillNo");
        //幂等性判断 标准：判断交易流水是否存在
        Boolean isSaveTransFlow = transFlowService.isSaveTransFlow(agentBillNo);
        if(isSaveTransFlow){
            return "success";
        }


        String bindCode = (String)map.get("bindCode");
        //提现金额（与商户传过来的一致）
        String fetchAmt = (String)map.get("fetchAmt");
        userInfoMapper.updateAmount(bindCode,new BigDecimal("-"+fetchAmt),new BigDecimal(0));
        //记录交易流水
        TransFlowBO transFlowBO = new TransFlowBO(
                agentBillNo,
                bindCode,
                new BigDecimal(fetchAmt),
                TransTypeEnum.RECHARGE,
                "提现"
        );
        transFlowService.saveTransFlow(transFlowBO);
        return "success";
    }
}
